package basic.study.wantOffer.chapter5;

import java.util.List;

/**
 * @ClassName Problem58
 * @Description
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/13 16:01
 * @Version 1.0
 */
public class Problem58 {
    /**
     * 我自己的省力做法
     * @param sentence
     * @return
     */
    public String ReverseSentence(String sentence) {
        //首先反转整个句子
        String temp = new StringBuilder(sentence).reverse().toString();
        //然后空格分割
        String[] temps = temp.split(" ");
        //对每个String翻转拼接
        String result = "";
        for (int i = 0; i < temps.length; i++) {
            result += new StringBuilder(temps[i]).reverse().toString();
            if (i != temps.length -1) {
                result += " ";
            }
        }
        return result;
    }
    /**
     * 网上的方法
     */
    public String ReverseSentence1(char[] chars) {
        if (chars == null || chars.length <= 0) {
            return String.valueOf(chars);
        }
        //翻转整个句子
        reverseSb(chars, 0, chars.length -1);
        //翻转单词 （指针指向单词的第一个和最后一个）
        int start = 0;
        int end = 0;
        while (start < chars.length) {
            while (end < chars.length && chars[end] != ' ') {
                end++;
            }
            reverseSb(chars, start, end);
            start += end;
        }
        return String.valueOf(chars);
    }

    private void reverseSb(char[] chars, int start, int end) {
        while (start < end) {
            char temp = chars[start];
            chars[start++] = chars[end];
            chars[end--] = temp;
        }
    }

    class Problem58_2 {
        public String leftRorareString(char[] chars, int n) {
            if (chars == null || chars.length <= 0) {
                return String.valueOf(chars);
            }
            if (n <= 0 || n > chars.length) {
                return String.valueOf(chars);
            }
            reverseSb(chars, 0, n-1);
            reverseSb(chars, n, chars.length-1);
            reverseSb(chars, 0, chars.length -1);
            return String.valueOf(chars);
        }
    }
}
